//
//  UIControl+Login.m
//  NEDCategory
//
//  Created by 000 on 2022/1/4.
//

#import "UIControl+Login.h"
#import <objc/runtime.h>
#import <objc/message.h>
#import <NEDConstant/NEDConstant+Method.h>
#import <NEDApp/NEDApp+Mediator.h>

@implementation UIControl (Login)


+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        SEL originalSelector = @selector(sendAction:to:forEvent:);
        SEL swizzledSelector = @selector(ned_loginSendAction:to:forEvent:);
                
        ned_swizzleMethod([self class],originalSelector,swizzledSelector);
    });
}

- (BOOL)ned_loginedContinueAction{
    return [objc_getAssociatedObject(self,@selector(ned_loginedContinueAction)) boolValue];
}
- (void)setNed_loginedContinueAction:(BOOL)ned_loginedContinueAction{
    objc_setAssociatedObject(self, @selector(ned_loginedContinueAction), @(ned_loginedContinueAction), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)ned_shouldLogin{
    return [objc_getAssociatedObject(self,@selector(ned_shouldLogin)) boolValue];
}
- (void)setNed_shouldLogin:(BOOL)ned_shouldLogin{
    objc_setAssociatedObject(self, @selector(ned_shouldLogin), @(ned_shouldLogin), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    NSSet * tags = [self allTargets];
    if(tags.count == 0){
        //无事件 添加一个时间 设置的时候 可以走sendAction u回调
        [self addTarget:nil action:@selector(actionNULL) forControlEvents:(UIControlEventTouchUpInside)];
    }
}

- (void)actionNULL{}

- (void)ned_loginSendAction:(SEL)action to:(id)target forEvent:(UIEvent*)event
{
    NSSet * tags = [self allTargets];
    if(tags.count > 1){
        if(action == @selector(actionNULL)){
            return;
        }
    }
    WS(weakSelf)
    if (self.ned_shouldLogin && !APP.uinfo.isLogin) {
        if(APP.mediator.helper && [APP.mediator.helper respondsToSelector:@selector(login_doSuccess:)]){
            [APP.mediator.helper login_doSuccess:^{
                [weakSelf yh_continueActionWith:NSStringFromSelector(action) WithTarget:target];
            }];
        }
        return;
    }
    
    [self ned_loginSendAction:action to:target forEvent:event];
}


- (void)yh_continueActionWith:(NSString *)selectorName WithTarget:(id)target{
    if (self.ned_loginedContinueAction) {
        SEL sel = NSSelectorFromString(selectorName);
        if ([target respondsToSelector:sel]){
            if ([selectorName hasSuffix:@":"]){
                ((void (*) (id, SEL, id)) (void *)objc_msgSend)(target, sel, self);
            }
            else{
                ((void (*) (id, SEL)) (void *)objc_msgSend)(target, sel);
            }
        }
    }
}


@end
